/**
 * 每天早上9点生成项目报告，并发送邮件
 */

const _ = require('lodash');
const ms = require('ms');
const moment = require('moment');

module.exports = {
  schedule: {
    immediate: true,
    // cron: '0 0 9 * * *', // 每天早上9点
    cron: '0 10 0 * * *', // 每天凌晨0点10分生成这天的报告
    type: 'worker', // 指定一个 worker 执行
    env: ['prod'],// 在prod环境才执行
  },
  async task(ctx) {
    const app = ctx.app;
    const {lte, gte} = app.Sequelize.Op;
    const {Project, Report} = app.model;
    const today = moment().endOf('day');
    const created_at = today.format('YYYY-MM-DD');
    const projects = await Project.findAll({
      where: {
        start_at: {[lte]: Date.now()},
        end_at: {[gte]: today.toDate()},
      },
      include: [{model: Report, required: false, where: {created_at}}],
    });
    for (let i = 0; i < projects.length; i++) {
      const project = projects[i];
      if (project.reports && project.reports.length > 0)
        continue;
      Report.create({project_id: project.id, created_at});
    }
  },
};